/* common.js */
/*****************************************************************************/
/* USER SESSION CONTROL
/*****************************************************************************/
if (typeof SwJs == "undefined") SwJs =
{
    StaticHost: "http://cdn1.static.spankwire.com",
    SetTitle: function(s) {
        $("#main-area .header-bar h1").html(s);
    }
};
if (typeof SwJs.Session == "undefined") SwJs.Session = {
    SexPref: null,
    UserId: null,
    IsPremium: false,
    IsPlatinum: false,
    LoginUrl: null,
    LogoutUrl: null,
    PrefUrls: [],
    callback: null,
    Init: function (sexPref, userId, premium, platinum, activeFilter) {
        this.SexPref = sexPref;
        this.UserId = userId;
        this.IsPremium = premium || platinum;
        this.IsPlatinum = platinum;
        $("#ddSexPref").val(sexPref.toUpperCase()).css("visibility", "visible");

        if (sexPref.toUpperCase() == "GAY") {
        }
        else if (sexPref.toUpperCase() == "TRANNY") {
        }
        else {
        }

        if (this.UserId != "")
            $(".htmlBody").addClass("logged");
        if (activeFilter != "None")
            $("#nav" + activeFilter).addClass("active");
    },
    Upgrade: function (sender, event) {
        var url = SwAx.GetUpgradeLink().value;
        if (url == null)
            alert("An error occured, please refresh the page and try again.");
        else if (url == "")
            alert("You are already logged a platinum user, please refresh the page and try again.");
        else
            window.location = url;

        return SpkJs.Event.CancelClick(event);
    },
    RegReturnUrl: function (url) {
        SpkJs.Cookies.Create("regurl", url);
    },
    ShowLoginGeneric: function (sender, event) {
        this.ShowLogin("Login to enable additional features on Spankwire.com", null);
        return SpkJs.Event.CancelClick(event);
    },
    CheckLoginProfile: function (sender, event) {
        if (this.UserId == "") {
            this.LoginUrl = sender.href;
            this.ShowLogin("You must login to view your profile.", null);
            return SpkJs.Event.CancelClick(event);
        }
        return true;
    },
    ShowLogin: function (message, callback) {
        var logged = (SwJs.Session.UserId == "");
        if (logged)
            $("#splogin").html(" - Log in / Sign up");
        else {
            message += "<div class=\"upgrade-link\"><a href=\"#\" onclick=\"return SwJs.Session.Upgrade(this, event);\">Upgrade Now</a>";
            $("#splogin").html(" - Upgrade");
        }
        $("#overlay_login").toggleClass("upgrade", !logged);
        this.callback = callback;
        //SpkJs.Flash.SetVisibilityAll(false);
        //$("#tbPassword").replaceWith("<input type=\"text\" id=\"tbPassword\" onfocus=\"SwJs.Forms.ClearDefault(this)\" class=\"text\" value=\"Password\"/>");
        $("#tbUsername").val("");
        $("#tbPassword").val("");
        $("#login_message").html(message);
        this.LoginEnable(true);
        this.SetStatus("");
        SwJs.Overlay.show("login");
        $("#tbUsername").focus();
    },
    HideLogin: function () {
        // SpkJs.Flash.SetVisibilityAll(true);
        SwJs.Overlay.hide("login");
    },
    HidePlatinum: function () {
        SwJs.Overlay.hide("platinum");
    },
    CheckLogin: function (sender, event, message) {
        if (this.UserId == "") {
            this.LoginUrl = sender.href;
            this.ShowLogin(message, null);
            return SpkJs.Event.CancelClick(event);
        }
        return true;
    },
    LogoutEvents: [],
    LoginEvents: [],
    OnLogin: function (handler) {
        this.LoginEvents[this.LoginEvents.length] = handler;
    },
    OnLogout: function (handler) {
        this.LogoutEvents[this.LogoutEvents.length] = handler;
    },
    Logout: function (sender, event) {
        var result = SwAx.Logout().value;
        if (result != null && result.OperationSuccess) {
            this.UserId = "";
            this.IsPremium = false;
            this.IsPlatinum = false;
            $(".htmlBody").removeClass("logged");
            DeleteCookie("ssig_visitor");
            for (var i = 0; i < this.LogoutEvents.length; i++)
                this.LogoutEvents[i]();

            if (this.LogoutUrl != null)
                window.location = this.LogoutUrl;
        }
        return SpkJs.Event.CancelClick(event);
    },
    LoginEnable: function (enabled) {
        $("#overlay_login input, #overlay_login button").each(function () { this.disabled = !enabled; });
    },
    SetStatus: function (message) {
        $("#spLoginError").html(message);
    },
    btnLogin_Click: function (event) {
        var username = $("#tbUsername").val();
        var password = $("#tbPassword").val();

        if (username == "" || password == "") {
            this.SetStatus("Please enter your username and password.");
        }
        else {
            this.LoginEnable(false);
            this.SetStatus("<img src='" + SwJs.StaticHost + "/Template/img/progress/sm/snake-F2DCE8.gif' />&nbsp;Logging In...");
            var callbackRef = this;
            //SwAx.GetUserSalt(username, function(result) { callbackRef.AuthCallback1(result); });
            SwAx.Authenticate2(username, password, function (result) { callbackRef.AuthCallback2(result); });
        }
        return SpkJs.Event.CancelClick(event);
    },
    AuthCallback2: function (res) {
        var result = res.value;
        if (result.OperationSuccess) {
            if (result.LoginSuccess) {
                this.UserId = result.UserId;
                this.IsPremium = result.IsPremium;
                this.IsPremium = result.IsPremium || result.IsPlatinum;
                this.IsPlatinum = result.IsPlatinum;

                if (document.cookie.length > 0) {
                    var cname = "PlatinumDoNotRemindLater";
                    c_start = document.cookie.indexOf(cname + "=");
                    if (c_start != -1) {
                        c_start = c_start + cname.length + 1;

                        c_end = document.cookie.indexOf(";", c_start);
                        if (c_end == -1) c_end = document.cookie.length;

                        cvalue = unescape(document.cookie.substring(c_start, c_end));
                    }
                }

                if (result.IsPremium && !result.IsPlatinum && cvalue != "1") {
                    var exdate = new Date();
                    exdate.setDate(exdate.getDate() + 3);
                    document.cookie = "PremiumAlert=1;expires=" + exdate.toUTCString() + "; path=/";
                }
                SetCookie("ssig_visitor", "1", 30);
                try { ssig_visitor_property('spankwire_member_id', result.UserId); } catch (error) { }

                if (result.ReloadPage) window.location.reload(true);

                //if (result.AuxHtml != '') $("body").append(result.AuxHtml);
                $(".htmlBody").addClass("logged");
                $("#tbUsername").val("");
                $("#tbPassword").val("");
                this.RotateAds();

                for (var i = 0; i < this.LoginEvents.length; i++)
                    this.LoginEvents[i]();

                var cvalue = "";

                if (this.callback == null) {
                    if (this.LoginUrl != null) {
                        window.location = this.LoginUrl;
                    }
                    else {
                        this.HideLogin();
                    }
                }
                else {
                    this.HideLogin();
                    this.callback();
                }

                ShowPremiumModal();
                return;
            }
            else {
                this.SetStatus("Login Failed. " + result.Reason);
            }
        }
        else
            this.SetStatus("Login not available.  Please try again later.");

        this.LoginEnable(true);
        $("#tbUsername").focus();
    },
    AuthCallback1: function (res) {
        var result = res.value;
        var username = $("#tbUsername").val();
        var password = $("#tbPassword").val();

        if (result != null && result.OperationSuccess) {
            var pwhash = SpkJs.Cryptography.Hashing.SHA1(password + result.Salt);
            result = SwAx.Authenticate(username, pwhash).value;
            this.AuthCallback2(result);
        }
        else
            this.SetStatus("Login not available.  Please try again later.");

        this.LoginEnable(true);
        $("#tbUsername").focus();
    },
    PrefUrl: function (name, url) {
        this.PrefUrls[name] = url;
    },
    ChangePref: function (sender, event) {
        //window.location = this.PrefUrls[$(sender).val()];

        if ($(sender).val() == "STRAIGHT") {
        }
        else if ($(sender).val() == "GAY") {
        }
        else if ($(sender).val() == "TRANNY") {
        }
    },
    PlatinumDoNotRemindLater: function (sender, event) {
        // Write Remind later cookie
        var c_name = "PlatinumDoNotRemindLater";

        if ($("#tdPlatinumDoNotRemindLater").is(':checked')) {
            DeleteCookie(c_name);
        }
        else {
            SetCookie(c_name, "1", 30);
        }

        return SpkJs.Event.CancelClick(event);
    },
    RotateAds: function () {
        var articleId = null;
        if (typeof SwJs.Article != "undefined")
            articleId = SwJs.Article.Id;

        var result = SwAx.GetAds(false, articleId).value;

        if (result != null) {
            $("#header-ad").html(result.Leader);
            $("#sidebar-tower").html(result.Tower);
            $("#footer-ad").html(result.Footer);
            if (articleId != null) {
                $("#vidAdTop").html(result.VidBoxTop);
                $("#vidAdBottom").html(result.VidBoxBottom);
            }
        }
    }
};

if (typeof SwJs.Forms == "undefined") SwJs.Forms = {
    //  Clear input fields on focus if the value matches the default  value
    ClearDefault: function(el)
    {
        //alert(el.defaultValue + ' ' + el.type);
        if (el.defaultValue == el.value) el.value = "";
        //if (el.defaultValue == "Password") el.type = "password";
    }
};

if (typeof SwJs.Ajax == "undefined") SwJs.Ajax = {
    LoadingHTML: "<br /><img src='" + SwJs.StaticHost + "/Template/img/progress/sm/snake.gif' />&nbsp;Please wait while we load the contents...",
    SetLoading: function (containerName) {
        $("#" + containerName).html(SwJs.Ajax.LoadingHTML).show();
    }    
};

if (typeof SwJs.Search == "undefined") SwJs.Search = {
    TextDefault: "Search Spankwire",
    Text: "",
    Enter: function()
    {
        SwJs.Search.Text = $('#search-input')[0].value;
        SwJs.Search.Search();
    },
    Click: function(sender, event)
    {
        SwJs.Search.Search();
        return SpkJs.Event.CancelClick(event);
    },
    Search: function()
    {
        if (SwJs.Search.Text == "")
            $('#search-input')[0].focus();
        else
        {
            var s = SwJs.Search.Text.replace(/'/g, "\\'");
            try { ssig_searched_for(s); } catch (error) { }
            window.location.href = "/search/" + SwJs.Session.SexPref + "/keyword/" + encodeURIComponent(SwJs.Search.Text.replace(/\//g, " "));
        }
    },
    Focus: function(sender, event)
    {
        sender.value = SwJs.Search.Text;
        return SpkJs.Event.CancelClick(event);
    },
    Blur: function(sender, event)
    {
        SwJs.Search.Text = sender.value;
        sender.value = SwJs.Search.TextDefault;
        return SpkJs.Event.CancelClick(event);
    }
};

/*****************************************************************************/
/* WINDOW CONTROL 
/*****************************************************************************/

if (typeof SwJs.Overlay == "undefined") SwJs.Overlay = {
    show: function(name, allowResize) {
        SpkJs.Flash.SetVisibilityAll(false);
        objPageSize = SpkJs.Window.getSize();
        this.controlWindow(objPageSize.pageHeight + "px", "hidden");
        this.controlOverlay(name, "block", allowResize);
    },
    hide: function(name) {
        SpkJs.Flash.SetVisibilityAll(true);
        this.controlOverlay(name, "none");
        this.controlWindow("", "", false);
    },
    controlWindow: function(height, overflow) {

        var ie6 = jQuery.browser.msie && (jQuery.browser.version.indexOf('6.') == 0);
        
        bod = document.getElementsByTagName("body")[0];
        bod.style.height = height;
        if (ie6) bod.style.overflow = overflow;

        htm = document.getElementsByTagName("html")[0];
        htm.style.height = height;
        if (ie6) htm.style.overflow = overflow;

        bodc = document.getElementById("overlay_container");
        bodc.style.height = height;
        if (ie6) bodc.style.overflow = overflow;
    },
    controlOverlay: function(name, display, allowResize) {
        objPageSize = SpkJs.Window.getSize();
        objScroll = SpkJs.Window.getScrollPos();

        oConfirm = document.getElementById("overlay_" + name);
        oBackground = document.getElementById("overlay_background");

        //    if (oConfirm == null || oBackground == null) return false;

        oBackground.style.display = display;
        oBackground.style.top = objScroll.y + "px";
        oConfirm.style.display = display;

        var windowLeft = objPageSize.windowWidth;
        var windowTop = objPageSize.windowHeight;
        var confirmWidth = oConfirm.offsetWidth;
        var confirmHeight = oConfirm.offsetHeight;

        if (allowResize) {
            if (confirmWidth > windowLeft) {
                confirmWidth = windowLeft - 100;
                oConfirm.style.width = confirmWidth + "px";
            }
            if (confirmHeight > windowTop) {
                confirmHeight = windowTop - 125;
                oConfirm.style.height = confirmHeight + "px";
            }
        };

        var marginLeft = 0;
        var marginTop = 0;

        marginTop = (windowTop / 2) - (confirmHeight / 2);
        marginLeft = (windowLeft / 2) - (confirmWidth / 2);

        if (marginTop < 0) marginTop = 0;
        if (marginLeft < 0) marginLeft = 0;

        oConfirm.style.top = (marginTop + objScroll.y) + "px";
        oConfirm.style.left = marginLeft + "px";
    }
};

function getBlock(block) {
    document.getElementById("comments").innerHTML = document.getElementById("comment_block_" + block).innerHTML;

    if (PagesCount > 1) {
        document.getElementById("CommentPaging_1_" + CurrentPage).setAttribute("class", "");
        document.getElementById("CommentPaging_1_" + CurrentPage).setAttribute("className", "");
        document.getElementById("CommentPaging_1_" + block).setAttribute("class", "active");
        document.getElementById("CommentPaging_1_" + block).setAttribute("className", "active");

        document.getElementById("CommentPaging_2_" + CurrentPage).setAttribute("class", "");
        document.getElementById("CommentPaging_2_" + CurrentPage).setAttribute("className", "");
        document.getElementById("CommentPaging_2_" + block).setAttribute("class", "active");
        document.getElementById("CommentPaging_2_" + block).setAttribute("className", "active");
    }

    CurrentPage = block;
}

function getNextPage() {
    if (CurrentPage < PagesCount) {
        getBlock(CurrentPage + 1);
    }
    else {
        getBlock(1);
    }
}

function getPrevPage() {
    if (CurrentPage > 1) {
        getBlock(CurrentPage - 1);
    }
    else {
        getBlock(PagesCount);
    }
}

function getCommentsDivs() {
    var divs = document.getElementsByTagName('div');
    var x = 0;

    for (var i = 0; i < divs.length; i++) {
        myID = divs[i].id;
        if (myID.indexOf("divComment_") >= 0) {
            CommentsArray[x] = myID;
            x++;
        }
    }
}

function CommentsSort(Asc) {
    CommentsArray.sort();
    if (!Asc) {
        Sort = false;
        CommentsArray.reverse();
        document.getElementById("aComOldest_First").setAttribute("class", "");
        document.getElementById("aComOldest_First").setAttribute("className", "");
        document.getElementById("aComNewest_First").setAttribute("class", "active");
        document.getElementById("aComNewest_First").setAttribute("className", "active");
    }
    else {
        Sort = true;
        document.getElementById("aComOldest_First").setAttribute("class", "active");
        document.getElementById("aComOldest_First").setAttribute("className", "active");
        document.getElementById("aComNewest_First").setAttribute("class", "");
        document.getElementById("aComNewest_First").setAttribute("className", "");
    }

    var myhtml = "";

    if (ShowAll) {
        document.getElementById("aComShowAll").setAttribute("class", "active");
        document.getElementById("aComShowAll").setAttribute("className", "active");

        for (i = 0; i < CommentsArray.length; i++) {
            myhtml += "<div class=\"comment-wrap\" id=\"" + CommentsArray[i] + "\">\n";
            myhtml += document.getElementById(CommentsArray[i]).innerHTML;
            myhtml += "</div>\n";
        }
        document.getElementById("comments").innerHTML = myhtml;
    }
    else {
        document.getElementById("aComShowAll").setAttribute("class", "");
        document.getElementById("aComShowAll").setAttribute("className", "");

        var BlockCount = 0;
        var ComCount = 0;

        BlocksArray = new Array();

        for (i = 0; i <= CommentsArray.length; i++) {
            if ((i == CommentsArray.length || ComCount == PageSize) && myhtml != "") {
                BlocksArray[BlockCount] = myhtml;
                myhtml = "";
                BlockCount++;
                ComCount = 0;

                if (i == CommentsArray.length) break;
            }

            myhtml += "<div class=\"comment-wrap\" id=\"" + CommentsArray[i] + "\">\n";
            myhtml += document.getElementById(CommentsArray[i]).innerHTML;
            myhtml += "</div>\n";
            ComCount++;
        }

        if (BlockCount > 0) {
            for (i = 0; i < BlocksArray.length; i++) {
                j = i + 1;
                document.getElementById("comment_block_" + j).innerHTML = BlocksArray[i];
            }
        }

        getBlock(1);
    }
}

function ShowAllComments() {
    ShowAll = ShowAll ? false : true;
    CommentsSort(Sort);

    if (!ShowAll) {
        document.getElementById("Pager1").style.display = '';
        document.getElementById("Pager2").style.display = '';
    }
    else {
        document.getElementById("Pager1").style.display = 'none';
        document.getElementById("Pager2").style.display = 'none';
    }
}

function ShowPremiumModal() {
    // Read the cookie
    var c_name = "PremiumAlert";
    var c_value = "";

    var c_value = GetCookie(c_name);

    if (c_value == "1") {
        SwJs.Overlay.show("platinum");
        pageTracker._trackEvent('Platinum', 'Reminder Pop display');
        DeleteCookie(c_name);
    }
}

function SetCookie(cname, cvalue, expiryDays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiryDays);
    document.cookie = cname + "=" + cvalue + ";expires=" + exdate.toUTCString() + "; path=/";
}

function GetCookie(cname) {
    var cvalue = "";

    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(cname + "=");
        if (c_start != -1) {
            c_start = c_start + cname.length + 1;

            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;

            cvalue = unescape(document.cookie.substring(c_start, c_end));
        }
    }

    return cvalue;
}

function DeleteCookie(cname) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() - 1);
    document.cookie = cname + "=;expires=" + exdate.toUTCString();
}

/* BEGIN Click Truth Helper Library version 1.2     10/23/2010 */

function ssig_generic_link(ssig_fn, args) {
    try {
        var link = args[0];
        eval(ssig_fn + "(ssig_arg_slice(args,1))");
        if (link.target == '_blank') {
            setTimeout('window.open("' + link.href + '")', 100);
        } else {
            setTimeout('document.location = "' + link.href + '"', 100);
        }
        return false;
    } catch (err) {
        return true;
    }
}

function ssig_link_tag_selection() {
    return ssig_generic_link('ssig_tag_selection', ssig_link_tag_selection.arguments);
}

function ssig_link_tagged_content() {
    return ssig_generic_link('ssig_tagged_content', ssig_link_tagged_content.arguments);
}

function ssig_link_site_event() {
    return ssig_generic_link('ssig_site_event', ssig_link_site_event.arguments);
}

function ssig_link_countable_event() {
    return ssig_generic_link('ssig_countable_event', ssig_link_countable_event.arguments);
}

function ssig_link_offsite_event() {
    return ssig_generic_link('ssig_offsite_event', ssig_link_offsite_event.arguments);
}

function ssig_link_visitor_property() {
    return ssig_generic_link('ssig_visitor_property', ssig_link_visitor_property.arguments);
}

function ssig_link_decision_selection() {
    return ssig_generic_link('ssig_decision_selection', ssig_link_decision_selection.arguments);
}

function ssig_link_searched_for() {
    return ssig_generic_link('ssig_seached_for', ssig_link_searched_for.arguments);
}

/* perform a slice on an args object, which is 'array-like' but has no slice fn*/
function ssig_arg_slice(args, start_at) {
    var result = [];
    for (var i = start_at; i < args.length; i++) {
        result.push(args[i])
    }
    return result;
}
/* END Click Truth Helper Library version 1.2     10/23/2010 */

